/**
 * 用户模型
 * 用于用户认证和个人信息管理
 */

const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const config = require('../config');

// 用户模型定义
const UserSchema = new mongoose.Schema({
    username: {
        type: String,
        required: [true, '请提供用户名'],
        unique: true,
        trim: true,
        minlength: [3, '用户名至少需要3个字符'],
        maxlength: [20, '用户名不能超过20个字符']
    },
    email: {
        type: String,
        required: [true, '请提供邮箱'],
        unique: true,
        match: [
            /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
            '请提供有效的邮箱地址'
        ]
    },
    password: {
        type: String,
        required: [true, '请提供密码'],
        minlength: 6,
        select: false
    },
    avatar: {
        type: String,
        default: 'default-avatar.png'
    },
    role: {
        type: String,
        enum: ['user', 'admin'],
        default: 'user'
    },
    bio: {
        type: String,
        maxlength: [200, '个人简介不能超过200个字符']
    },
    favoriteGames: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Game'
    }],
    createdAt: {
        type: Date,
        default: Date.now
    },
    updatedAt: {
        type: Date,
        default: Date.now
    }
});

// 密码加密中间件
UserSchema.pre('save', async function(next) {
    // 仅在密码被修改时执行
    if (!this.isModified('password')) {
        next();
    }
    
    // 生成盐值并加密密码
    const salt = await bcrypt.genSalt(10);
    this.password = await bcrypt.hash(this.password, salt);
    
    // 更新时间
    this.updatedAt = Date.now();
    
    next();
});

// 验证密码方法
UserSchema.methods.matchPassword = async function(enteredPassword) {
    return await bcrypt.compare(enteredPassword, this.password);
};

// 生成JWT令牌
UserSchema.methods.generateAuthToken = function() {
    return jwt.sign(
        { id: this._id },
        config.jwt.secret,
        { expiresIn: config.jwt.expiresIn }
    );
};

// 过滤敏感数据
UserSchema.methods.toJSON = function() {
    const user = this.toObject();
    delete user.password;
    return user;
};

module.exports = mongoose.model('User', UserSchema); 